package menus;
import gui.BasketWindow;
import gui.CheckoutWindow;
import gui.CustomTable;
import gui.CustomTableModel;
import gui.ExceptionListener;
import gui.LoginWindow;
import gui.MainView;
import gui.RegistrationWindow;
import gui.SearchWindow;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;

import database.CustData;
import database.ManagerData;
import database.OracleConnection;
import database.PosData;

import java.sql.*;
import java.text.*;
import java.util.Calendar;
import java.util.Date;

public class CustMenu extends MenuSuperclass implements ActionListener, ExceptionListener
{
    private PosData transaction = null;
    private CustData cust = null;
    private ManagerData items = null;
    private String recString = null;
    private int orders;
    
    public CustMenu(MainView mv)
    {
        this.mv = mv;
        // need this for receipt numbers
        transaction = new PosData();
        transaction.addExceptionListener(this);
        cust = new CustData();
        cust.addExceptionListener(this);
        // need this to adjust inventory
        items = new ManagerData();
        items.addExceptionListener(this);
        orders = 0;
    }

    
    // methods called by different menu items... np = new purchase, cp = continue purchase, etc.
    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand();
        
        if (actionCommand.equals("log"))
        {
            int recNum = transaction.getMaxReceipt();
        	if (transaction.isPurDateNull(recNum)) {
                mv.updateStatusBar("Finish last purchase first.");
            }else{
            	LoginWindow iDialog = new LoginWindow(mv);
            	iDialog.pack();
            	mv.centerWindow(iDialog);
            	iDialog.setVisible(true);
            	showTransaction(transaction.getMaxReceipt());
            	mv.updateStatusBar("Purchase #" + transaction.getMaxReceipt());
            	return;
            }
        }
        
        if (actionCommand.equals("reg")){
        	RegistrationWindow iDialog = new RegistrationWindow(mv);
        	iDialog.pack();
        	mv.centerWindow(iDialog);
        	iDialog.setVisible(true);
        	
        	return;
        }
        if (actionCommand.equals("search")){
        	SearchWindow iDialog = new SearchWindow(mv);
        	iDialog.pack();
        	mv.centerWindow(iDialog);
        	iDialog.setVisible(true);
        	return;
        }
        if (actionCommand.equals("add")){
        	BasketWindow iDialog = new BasketWindow(mv);
        	iDialog.pack();
        	mv.centerWindow(iDialog);
        	iDialog.setVisible(true);
        	return;
        }
        if (actionCommand.equals("chkout")){
        	message("Total Purchase", "$"+transaction.getTotalPurchase(transaction.getMaxReceipt()));
        	CheckoutWindow iDialog = new CheckoutWindow(mv);
        	iDialog.pack();
        	mv.centerWindow(iDialog);
        	iDialog.setVisible(true);
        	return;
        }
        
        // getting rid of all this just need it as a reference
        if (actionCommand.equals("np"))
        {
        	// new purchase needs new rec# and an entry in the purchase table before items can be added
        	// should this be rolled back if purchase is zero items or is cancelled? (yes but don't bother)
        	int recNum = transaction.getMaxReceipt();
        	
        	if (transaction.isPurDateNull(recNum)) {
            mv.updateStatusBar("Finish last purchase first.");
        	} else {
            recNum++;
        	// show items already in transaction (blank)
            showTransaction(recNum);
          	// add entry to purchase db
        	transaction.addPurchase(recNum);
            // set receipt # for transaction form
        	recString = String.valueOf(recNum);
        	TransactionDialog iDialog = new TransactionDialog(mv);
            iDialog.pack();
            mv.centerWindow(iDialog);
            iDialog.setVisible(true);
            return;
        	}
        }
        
        if (actionCommand.equals("cp"))
        {
        	int recNum = transaction.getMaxReceipt();
        	if (transaction.isPurDateNull(recNum)) {
        	// continue purchase looks up last rec# to add more items
        	// concurrent usage of db would need this value cached per terminal
        	// show items already in transaction
            showTransaction(recNum);
            // set receipt # for transaction form
          	recString = String.valueOf(recNum);
        	TransactionDialog iDialog = new TransactionDialog(mv);
            iDialog.pack();
            mv.centerWindow(iDialog);
            iDialog.setVisible(true);
            return;
        	} else {
        		mv.updateStatusBar("No open purchases.");
        	}
        }
        
        if (actionCommand.equals("fp"))
        {
        	int recNum = transaction.getMaxReceipt();
        	// is purchase open?
        	if (transaction.isPurDateNull(recNum)) {
        	// then set ship date to indicate purchase is closed
        	transaction.setPurDate(recNum);
    		mv.updateStatusBar("Closed Receipt #"+recNum+".");

        	// debit inventory
        	// show a subtotal
        	// clear table
        	
            return;
    	} else {
    		mv.updateStatusBar("No open purchases.");
    	}
        }

        // reverse of above methods with more checks
        if (actionCommand.equals("nr"))
        {
            
            return;
        }
        if (actionCommand.equals("cr"))
        {
            
            return;
        }
        
        
        if (actionCommand.equals("fr"))
        {
            
            return;
        }
    }
    
    private void showTransaction(int rec)
    {
        ResultSet rs = transaction.showTransaction(rec);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    
    private void showItemsWithCategory(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithCategory(category, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithTitle(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithTitle(title, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithSinger(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithSinger(singer, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithCatAndTit(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithCatAndTit(category, title, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithCatAndSing(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithCatAndSing(category, singer, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithCatTitSing(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithCatTitSing(category, title, singer, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    private void showItemsWithTitAndSing(String category, String title, String singer, int quantity){
    	ResultSet rs = cust.showItemsWithTitAndSing(title, singer, quantity);
        CustomTableModel model = new CustomTableModel(transaction.getConnection(), rs);
        CustomTable data = new CustomTable(model);
        model.addExceptionListener(this);
        data.addExceptionListener(this);
        mv.addTable(data);
    }
    
    
    class TransactionDialog extends JDialog implements ActionListener
    {
    	//private String recNum = recString;
        //private JTextField recField = new JTextField(recNum, 10);
        private JTextField upcField = new JTextField(15);
        private JTextField qtyField = new JTextField(15);
        
        public TransactionDialog(JFrame parent)
        
        {
            super(parent, "Purchase/Return Item", true);
            setResizable(false);
            JPanel contentPane = new JPanel(new BorderLayout());
            setContentPane(contentPane);
            contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            JPanel inputPane = new JPanel();
            String title = "Receipt #: "+recString;
            inputPane.setBorder(BorderFactory.createCompoundBorder(
                         new TitledBorder(new EtchedBorder(), title),
                         new EmptyBorder(5, 5, 5, 5)));
            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            inputPane.setLayout(gb);
            
//            JLabel label= new JLabel("Receipt #: "+recString, SwingConstants.RIGHT);
//            c.gridwidth = GridBagConstraints.RELATIVE;
//            c.insets = new Insets(0, 0, 0, 5);
//            c.anchor = GridBagConstraints.EAST;
//            gb.setConstraints(label, c);
//            inputPane.add(label);
//            c.gridwidth = GridBagConstraints.REMAINDER;
//            c.insets = new Insets(0, 0, 0, 0);
//            c.anchor = GridBagConstraints.WEST;
//            gb.setConstraints(recField, c);
//            inputPane.add(recField);
//            
            JLabel label = new JLabel("UPC: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(upcField, c);
            inputPane.add(upcField);
            
            label = new JLabel("Quantity: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(qtyField, c);
            inputPane.add(qtyField);
               
            // set last field action command for enter key
            qtyField.addActionListener(this);
            qtyField.setActionCommand("OK");
            
            // ok/cancel button pane
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));
            JButton OKButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            OKButton.addActionListener(this);
            OKButton.setActionCommand("OK");
            cancelButton.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        dispose();
                    }
                });
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(OKButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
            buttonPane.add(cancelButton);
            contentPane.add(inputPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            addWindowListener(new WindowAdapter()
                {
                    public void windowClosing(WindowEvent e)
                    {
                        dispose();
                    }
                });
        }
        
        
        public void actionPerformed(ActionEvent e)
        {
            String actionCommand = e.getActionCommand();
            if (actionCommand.equals("OK"))
            {
                if (validateInsert() != VALIDATIONERROR)
                {
                    dispose();
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane errorPopup = new JOptionPane();
                    errorPopup.showMessageDialog(this, "Invalid Input",
                                    "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
            
        }
        private int validateInsert()
        {
        
            //Integer rec = Integer.valueOf(recString.getText().trim());
        	Integer rec = Integer.valueOf(recString);
            Integer upc = Integer.valueOf(upcField.getText().trim());
            Integer qty = Integer.valueOf(qtyField.getText().trim());
            
        	if (transaction.findReceiptAndUPC(rec, upc)) {
        		mv.updateStatusBar("That tuple already exists, adjusting...");
        		transaction.adjustPurItem(rec, upc, qty);
                showTransaction(rec);
        		return OPERATIONSUCCESS;
      		        		
        	}
            
            
            mv.updateStatusBar("Processing transaction...");
          transaction.addPurItem(rec, upc, qty);
        	
        	  mv.updateStatusBar("Operation successful.");
        showTransaction(rec);
        return OPERATIONSUCCESS;
        	
        	
        	
        	
//        	try
//            {
//                Integer          supc;
//                String         sname;
//                
//                if (upcField.getText().trim().length() != 0 && sNameField.getText().trim().length() != 0)
//                {
//                    supc = Integer.valueOf(upcField.getText().trim());
//                    sname = sNameField.getText().trim();
//                    
//                    if (singer.findSingerAndUPC(supc.intValue(), sname))
//                    {
//                        Toolkit.getDefaultToolkit().beep();
//                        mv.updateStatusBar("That tuple already exists!");
//                        return OPERATIONFAILED;
//                    }
//                }
//                else
//                {
//                    return VALIDATIONERROR;
//                }
//                if (sNameField.getText().trim().length() != 0)
//                {
//                    sname = sNameField.getText().trim();
//                }
//                else
//                {
//                    return VALIDATIONERROR;
//                }
//                                mv.updateStatusBar("Inserting singer...");
//                if (singer.insertSinger(supc, sname))
//                {
//                    mv.updateStatusBar("Operation successful.");
//                    editAllSingers();
//                    return OPERATIONSUCCESS;
//                }
//                else
//                {
//                    Toolkit.getDefaultToolkit().beep();
//                    mv.updateStatusBar("Operation failed.");
//                    return OPERATIONFAILED;
//                }
//            }
//            catch (NumberFormatException ex)
//            {
//                return VALIDATIONERROR;
//            }
        }
    }
 class SearchWindow extends JDialog implements ActionListener
    {
    	// MvbOracleConnection represents a connection to an Oracle database
    	private OracleConnection mvb = OracleConnection.getInstance();



    	// components of the registration window
    	private JTextField categoryField = new JTextField(15);	  
    	private JTextField titleField = new JTextField(15);
    	private JTextField singerField = new JTextField(15);
  //  	private JTextField quantityField = new JTextField(15);
    	private JLabel categoryLabel = new JLabel("Enter category:  ");
    	private JLabel titleLabel = new JLabel("Enter title:  ");
    	private JLabel singerLabel = new JLabel("Enter singer:  ");
 //   	private JLabel quantityLabel = new JLabel("Enter quantity:  ");
    	private JButton searchButton = new JButton("Search");


    	/*
    	 * Default constructor. The registration window is constructed here.
    	 */
    	public SearchWindow(JFrame parent)
    	{
    		super(parent, "Item Search", true);
    		setResizable(false);


    		// content pane for the registration window
    		JPanel searchPane = new JPanel();
    		setContentPane(searchPane);


    		/*
    		 * layout components using the GridBag layout manager
    		 */ 

    		GridBagLayout gb = new GridBagLayout();
    		GridBagConstraints c = new GridBagConstraints();

    		searchPane.setLayout(gb);
    		searchPane.setBorder(BorderFactory.createEmptyBorder(22, 12, 11, 11));

    		// place the username label 
    		c.gridwidth = GridBagConstraints.RELATIVE;
    		c.insets = new Insets(10, 10, 0, 0);
    		gb.setConstraints(categoryLabel, c);
    		searchPane.add(categoryLabel);

    		// place the text field for the username 
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.insets = new Insets(10, 0, 0, 10);
    		gb.setConstraints(categoryField, c);
    		searchPane.add(categoryField);

    		// place password label
    		c.gridwidth = GridBagConstraints.RELATIVE;
    		c.insets = new Insets(10, 10, 0, 0);
    		gb.setConstraints(titleLabel, c);
    		searchPane.add(titleLabel);

    		// place the password field 
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.insets = new Insets(10, 0, 0, 10);
    		gb.setConstraints(titleField, c);
    		searchPane.add(titleField);

    		// place name label
    		c.gridwidth = GridBagConstraints.RELATIVE;
    		c.insets = new Insets(10, 10, 0, 0);
    		gb.setConstraints(singerLabel, c);
    		searchPane.add(singerLabel);

    		// place the name field 
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.insets = new Insets(10, 0, 0, 10);
    		gb.setConstraints(singerField, c);
    		searchPane.add(singerField);
    		
//    		// place address label
//    		c.gridwidth = GridBagConstraints.RELATIVE;
//    		c.insets = new Insets(10, 10, 0, 0);
//    		gb.setConstraints(quantityLabel, c);
//    		searchPane.add(quantityLabel);
//
//    		// place the address field 
//    		c.gridwidth = GridBagConstraints.REMAINDER;
//    		c.insets = new Insets(10, 0, 0, 10);
//    		gb.setConstraints(quantityField, c);
//    		searchPane.add(quantityField);
//    		
    		
    		// place the register button
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.insets = new Insets(10, 10, 5, 10);
    		c.anchor = GridBagConstraints.CENTER;
    		gb.setConstraints(searchButton, c);
    		searchPane.add(searchButton);

    		// end of layout

    		// Register password field and OK button with action event handler.
    		// An action event is generated when the return key is pressed while 
    		// the cursor is in the password field or when the OK button is pressed.
    		searchButton.addActionListener(this);

    		// anonymous inner class for closing the window
    		addWindowListener(new WindowAdapter() 
    		{
    			public void windowClosing(WindowEvent e) 
    			{ 
    				//System.exit(0); 
    			}
    		});

    		// initially, place the cursor in the username text field
    		categoryField.requestFocus();	

    		// auto-login:
    		mvb.connect("ora_o4b8", String.valueOf("a29458957"));

    	}


    	/*
    	 * event handler register button
    	 */ 	    
    	public void actionPerformed(ActionEvent e) 
    	{
    		if((categoryField.getText().trim().length() != 0) && (titleField.getText().trim().length() == 0)
    				&& (singerField.getText().trim().length() == 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithCategory(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
    				
    			
    		}
    		else if((categoryField.getText().trim().length() == 0) && (titleField.getText().trim().length() != 0)
    				&& (singerField.getText().trim().length() == 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithTitle(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
   			
    		}
    		else if((categoryField.getText().trim().length() == 0) && (titleField.getText().trim().length() == 0)
    				&& (singerField.getText().trim().length() != 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithSinger(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
   						0);
    				dispose();
    				
    			
    		}
    		else if((categoryField.getText().trim().length() != 0) && (titleField.getText().trim().length() != 0)
    				&& (singerField.getText().trim().length() == 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithCatAndTit(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
    				
    		}
    		else if((categoryField.getText().trim().length() != 0) && (titleField.getText().trim().length() == 0)
    				&& (singerField.getText().trim().length() != 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithCatAndSing(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
    				
    		}
    		else if((categoryField.getText().trim().length() != 0) && (titleField.getText().trim().length() != 0)
    				&& (singerField.getText().trim().length() != 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithCatTitSing(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
    				
    			
    		}
    		else if((categoryField.getText().trim().length() == 0) && (titleField.getText().trim().length() != 0)
    				&& (singerField.getText().trim().length() != 0)){
    			CustMenu cm = new CustMenu(mv);
    				cm.showItemsWithTitAndSing(categoryField.getText().trim(), titleField.getText().trim(), singerField.getText().trim(), 
    						0);
    				dispose();
    				
    			
    		}
    		
    		
    		
    	}
    }
 
class BasketWindow extends JDialog implements ActionListener
 {
 	// MvbOracleConnection represents a connection to an Oracle database
 	private OracleConnection mvb = OracleConnection.getInstance();



 	// components of the registration window
 	private JTextField upcField = new JTextField(15);	  
 	private JTextField quantityField = new JTextField(15);
 	private JLabel upcLabel = new JLabel("Enter upc:  ");
 	private JLabel quantityLabel = new JLabel("Enter quantity:  ");
 	private JButton addButton = new JButton("Add Item");


 	/*
 	 * Default constructor. The registration window is constructed here.
 	 */
 	public BasketWindow(JFrame parent)
 	{
 		super(parent, "Add Item to Basket", true);
 		setResizable(false);


 		// content pane for the registration window
 		JPanel addPane = new JPanel();
 		setContentPane(addPane);


 		/*
 		 * layout components using the GridBag layout manager
 		 */ 

 		GridBagLayout gb = new GridBagLayout();
 		GridBagConstraints c = new GridBagConstraints();

 		addPane.setLayout(gb);
 		addPane.setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11));

 		// place the username label 
 		c.gridwidth = GridBagConstraints.RELATIVE;
 		c.insets = new Insets(10, 10, 0, 0);
 		gb.setConstraints(upcLabel, c);
 		addPane.add(upcLabel);

 		// place the text field for the username 
 		c.gridwidth = GridBagConstraints.REMAINDER;
 		c.insets = new Insets(10, 0, 0, 10);
 		gb.setConstraints(upcField, c);
 		addPane.add(upcField);

 		// place address label
 		c.gridwidth = GridBagConstraints.RELATIVE;
 		c.insets = new Insets(10, 10, 0, 0);
 		gb.setConstraints(quantityLabel, c);
 		addPane.add(quantityLabel);

 		// place the address field 
 		c.gridwidth = GridBagConstraints.REMAINDER;
 		c.insets = new Insets(10, 0, 0, 10);
 		gb.setConstraints(quantityField, c);
 		addPane.add(quantityField);
 		
 		
 		// place the register button
 		c.gridwidth = GridBagConstraints.REMAINDER;
 		c.insets = new Insets(10, 10, 5, 10);
 		c.anchor = GridBagConstraints.CENTER;
 		gb.setConstraints(addButton, c);
 		addPane.add(addButton);

 		// end of layout

 		// Register password field and OK button with action event handler.
 		// An action event is generated when the return key is pressed while 
 		// the cursor is in the password field or when the OK button is pressed.
 		addButton.addActionListener(this);

 		// anonymous inner class for closing the window
 		addWindowListener(new WindowAdapter() 
 		{
 			public void windowClosing(WindowEvent e) 
 			{ 
 				//System.exit(0); 
 			}
 		});

 		// initially, place the cursor in the username text field
 		upcField.requestFocus();	

 		// auto-login:
 		mvb.connect("ora_o4b8", String.valueOf("a29458957"));

 	}


 	/*
 	 * event handler register button
 	 */ 	    
 	public void actionPerformed(ActionEvent e) 
 	{
 		
 		CustData cd = new CustData();
 		PosData transaction = new PosData();
 		if(cd.loggedIn(cd.getMaxReceipt())!=0 && (transaction.isPurDateNull(cd.getMaxReceipt()))){
 			

 		int Uppc = Integer.valueOf(upcField.getText().trim());
 		int quant = Integer.valueOf(quantityField.getText().trim());
 		if(Uppc != 0 && quant != 0){
 			if(cd.findStock(Uppc) >= (quant + cd.quantityPurchasing(cd.getMaxReceipt(),Uppc))){
 				if (transaction.findReceiptAndUPC(cd.getMaxReceipt(), Uppc)) {
 					mv.updateStatusBar("That UPC already exists... adjusted quantity.");
 					transaction.adjustPurItem(cd.getMaxReceipt(), Uppc, quant);
 					showTransaction(cd.getMaxReceipt());
 					dispose();
 				}else{
 					int recNum = cd.getMaxReceipt();
 					cd.addPurchaseItem(recNum, Uppc, quant);
 					showTransaction(recNum);
 					dispose();
 				}
 			}else{
 				message("You selected too much quantity! Select " + (cd.findStock(Uppc)-cd.quantityPurchasing(cd.getMaxReceipt(), Uppc)+1) + " quantity or lower!", mv.georgeIcon);
 			}
 			
 		}
 		}else{
 			message("You are not logged in!! You cannot buy until you log in!", mv.georgeIcon);
 		}
 		
 	}
 }

class CheckoutWindow  extends JDialog implements ActionListener
{
	// MvbOracleConnection represents a connection to an Oracle database
	private OracleConnection mvb = OracleConnection.getInstance();



	// components of the registration window
	private JTextField cardField = new JTextField(15);	  
	private JTextField expField = new JTextField(15);
	private JLabel cardLabel = new JLabel("Enter Card Number:  ");
	private JLabel expLabel = new JLabel("Enter Expiry Year (YYYY):  ");
	private JButton checkoutButton = new JButton("Checkout");


	/*
	 * Default constructor. The registration window is constructed here.
	 */
	public CheckoutWindow(JFrame parent)
	{
		super(parent, "Checkout", true);
		setResizable(false);


		// content pane for the registration window
		JPanel checkoutPane = new JPanel();
		setContentPane(checkoutPane);


		/*
		 * layout components using the GridBag layout manager
		 */ 

		GridBagLayout gb = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();

		checkoutPane.setLayout(gb);
		checkoutPane.setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11));

		// place the username label 
		c.gridwidth = GridBagConstraints.RELATIVE;
		c.insets = new Insets(10, 10, 0, 0);
		gb.setConstraints(cardLabel, c);
		checkoutPane.add(cardLabel);

		// place the text field for the username 
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.insets = new Insets(10, 0, 0, 10);
		gb.setConstraints(cardField, c);
		checkoutPane.add(cardField);

		// place address label
		c.gridwidth = GridBagConstraints.RELATIVE;
		c.insets = new Insets(10, 10, 0, 0);
		gb.setConstraints(expLabel, c);
		checkoutPane.add(expLabel);

		// place the address field 
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.insets = new Insets(10, 0, 0, 10);
		gb.setConstraints(expField, c);
		checkoutPane.add(expField);
		
		
		// place the register button
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.insets = new Insets(10, 10, 5, 10);
		c.anchor = GridBagConstraints.CENTER;
		gb.setConstraints(checkoutButton, c);
		checkoutPane.add(checkoutButton);

		// end of layout

		// Register password field and OK button with action event handler.
		// An action event is generated when the return key is pressed while 
		// the cursor is in the password field or when the OK button is pressed.
		checkoutButton.addActionListener(this);

		// anonymous inner class for closing the window
		addWindowListener(new WindowAdapter() 
		{
			public void windowClosing(WindowEvent e) 
			{ 
				//System.exit(0); 
			}
		});

		// initially, place the cursor in the username text field
		cardField.requestFocus();	

		// auto-login:
		mvb.connect("ora_o4b8", String.valueOf("a29458957"));

	}


	/*
	 * event handler register button
	 */ 	    
	public void actionPerformed(ActionEvent e) {
		CustData cd = new CustData();
		if(transaction.isPurDateNull(cd.getMaxReceipt())){
		if(Integer.valueOf(cardField.getText().trim().length()) == 16 && Integer.valueOf(expField.getText().trim()) >=2013){

			PosData transaction = new PosData();
			float cardno = Float.valueOf(cardField.getText().trim());
			int exp = Integer.valueOf(expField.getText().trim());
			cd.addCard(cd.getMaxReceipt(), cardno, exp);
			transaction.updateStockOnPurchase(cd.getMaxReceipt());
			transaction.setPurDate(cd.getMaxReceipt());
			orders++;
			int deliveredIn = deliveryDays(orders);
			message("Your delivery will be in " + deliveredIn + " days! \nHave a nice time!", mv.georgeIcon);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(new Date()); // Now use today date.
			c.add(Calendar.DATE, deliveredIn); // Adding n days
			cd.setExpDelDate(cd.getMaxReceipt(), transaction.convertToDate(sdf.format(c.getTime())));
			dispose();
			
		}else{
			
			message("Please enter a valid credit card!!", mv.georgeIcon);
		}
		
		}else{
			message("You are not logged in!! You cannot buy until you log in!", mv.georgeIcon);
			dispose();
		}
		
		
		
		
	}
}


public int deliveryDays(int ordersHold){
	int deliveredIn = 7;
	if (ordersHold<=2){
		return deliveredIn;
	}else{
		while(ordersHold>2){
			deliveredIn++;
			ordersHold--;
		}
		return deliveredIn;
	}
	
}




}
